<?php
namespace QuestionPlus\Service\Import\QuestionImport;

use QuestionPlus\Service\Import\QuestionImport\AbstractQuestionImport;

class FillQuestionImport extends AbstractQuestionImport
{
    private $pattern = array(
        'stem' => "【题干】",
        'answer' => "【答案】",
        'difficulty' => "【难度】",
        'score' => "【分数】",
        'analysis' => "【解析】"
    );

    protected function questionFilter ($questionText)
    {
        $pattern = implode('|', $this->pattern);
        $questionText = "【题干】" . $questionText;

        $isHas = preg_match_all("#({$pattern})(([\s\S](?!({$pattern})))*[\s\S])#u", $questionText, $matches, PREG_SET_ORDER);

        $questionFlags = array_flip($this->pattern);

        $question = array(
            'stem' => "",
            'answer' => "",
            'difficulty' => "一般",
            'score' => "2.0",
            'analysis' => ""
        );

        foreach ($matches as $value) {
            if (array_key_exists($value[1], $questionFlags)) {
                $question[$questionFlags[$value[1]]] = trim($value[2]);
            }
        }

        $question = $this->checkQuestion($question);

        return $this->fillFilter($question);
    }

    protected function answerFilter ($answerText)
    {
        $pattern = implode('|', $this->pattern);

        $isHas = preg_match_all("#({$pattern})(([\s\S](?!({$pattern})))*[\s\S])#u", $answerText, $matches, PREG_SET_ORDER);

        $questionFlags = array_flip($this->pattern);

        $question = array(
            'stem' => "",
            'answer' => "",
            'difficulty' => "一般",
            'score' => "2.0",
            'analysis' => ""
        );

        foreach ($matches as $value) {
            if (array_key_exists($value[1], $questionFlags)) {
                $question[$questionFlags[$value[1]]] = trim($value[2]);
            }
        }

        return $question;
    }

    private function fillFilter ($question)
    {
        if (empty($question['answer'])) {
            return $this->filter($question);
        }

        $answer = explode(' ', $question['answer']);

        $find = array_fill(0, count($answer), '___');
        $replace = array_map(function($ans){
            return '[[' . $ans . ']]';
        }, $answer);

        foreach ($answer as $key => $ans) {
            $question['stem'] = preg_replace("#___#", $replace[$key], $question['stem'], 1);
        }

        $question['answer'] = array_map(function($ans){
            return explode('|', $ans);
        }, $answer);

        return $this->filter($question);
    }

    protected function testQuestionByType($question)
    {
        
    }
}